<template>
  <section>
    <el-card class="box-card">
      <el-form
        v-if="!configData.closeSearch"
        ref="searchFormXH"
        :model="ruleForm"
        :rules="searchRules"
        :inline="true"
        size="mini"
      >
        <el-form-item
          v-for="(item, key) in searchForm"
          :key="key"
          :prop="key"
          :label-width="item.width"
        >
          <div v-if="item.widget === 'input'">
            <el-input v-model="ruleForm[key]" size="mini" :placeholder="item.name" />
          </div>
          <div v-else>
            <div
              :is="item.widget"
              v-model="ruleForm[key]"
              :default-value="item.defaultValue || ''"
              :config-data="item"
              :placeholder="item.name"
              @change="(e)=>{searchItemChange(e, key, item)}"
            />
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="cyan" icon="el-icon-search" size="mini" @click="searchDataValidate">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div style="margin: 10px 0">
      <slot name="top_button" />
    </div>
    <TableList
      :config-data="configData"
      :table-loading="tableLoading"
      :table-column="tableColumn"
      :table-data="tableData"
      @eventChange="eventChange"
      @selectionChange="handleSelectionChange"
    >
      <template slot="table_operation">
        <slot name="table_operation" />
      </template>
    </TableList>
    <div style="margin: 10px 0">
      <slot name="top_footer" />
    </div>
    <pagination
      v-if="!configData.closePagination"
      :pagination="queryData"
      :total="total"
      @page-change="pageChange"
    />
  </section>
</template>

<script>
// import { requestAPI } from '@/lib/commonMixin'
import commonComponents from './component'
import TableList from './tableList'

function allComponents() {
  return Object.assign({ TableList }, commonComponents)
}

export default {
  name: 'ModelIndex',
  components: allComponents(),
  props: {
    searchForm: {
      type: Object,
      default: function() {
        return {}
      }
    },
    tableColumn: {
      type: Object,
      default: function() {
        return {}
      }
    },
    configData: {
      type: Object,
      default: function() {
        return {}
      }
    },
    /*
    * @查询中间件
    * */
    searchMiddleware: {
      type: Function,
      default: function() {
        return function() { return }
      }
    }
  },
  data() {
    return {
      ruleForm: {},
      searchRules: {},
      // 组件筛选下拉框数据结合
      options: {},
      tableData: [],
      total: 0,
      queryData: {
        pageNum: 1,
        pageSize: 20
      },
      tableLoading: false,
      isReq: true// 允许访问，控制有缓存的时候请求两次接口问题
    }
  },
  created() {
    // 数据初始化
    this.defaultDataSet()
    // 用于缓存 现在不管用
    if (!this.configData.initNoQuery) {
      this.getTableData()
    }

    // 以下代码解决请求两次问题
    this.isReq = false
    // // 当前页面未缓存titile走created抛出
    // if (!this.$route.meta.cache) {
    //   this.$emit('changeTitle')
    // }
  },

  activated() {
    if (this.isReq) {
      this.searchDataValidate()
    } else {
      this.isReq = true
    }
    // 当前页面缓存titile走activated抛出
    if (this.$route.meta.cache) {
      this.$emit('changeTitle')
    }
  },
  methods: {
    tableInputChange(item, scope) {
      if (item.onblur) {
        item.onblur(scope)
      }
    },
    // 查询按钮调用
    submitHandleQuery() {
      this.queryData.pageNum = 1
      this.getTableData()
    },
    // 重置
    reset() {
      this.$refs['searchFormXH'].resetFields()
      this.searchDataValidate()
    },
    // 查询组件校验
    searchDataValidate() {
      this.$nextTick(() => {
        this.$refs['searchFormXH'].validate((valid) => {
          if (valid) {
            this.submitHandleQuery()
          } else {
            this.tableData = []
            this.total = 0
          }
        })
      })
    },
    // 查询组件默认数据
    defaultDataSet() {
      // 处理筛选框下拉数据
      const ruleObj = {}
      Object.keys(this.searchForm).forEach(key => {
        ruleObj[key] = this.searchForm[key]['rules'] || []
      })
      this.searchRules = ruleObj
      // 表单参数
      const keys = Object.keys(this.searchForm)
      const obj = {}
      keys.forEach(key => {
        obj[key] = this.searchForm[key].defaultValue || ''
      })
      this.ruleForm = Object.assign({}, this.ruleForm, obj)
      // 分页初始化
      this.queryData.pageSize = this.configData.pagination.pageSize
    },
    // 分页查询
    pageChange(pageNo, pageSize) {
      this.queryData.pageNum = pageNo
      this.queryData.pageSize = pageSize
      this.getTableData()
    },
    // 列表数据请求
    getTableData() {
      const params = Object.assign({}, this.ruleForm, this.queryData)
      this.searchMiddleware(params)
      this.tableLoading = true
      Object.keys(params).forEach(k => {
        if (!params[k]) {
          params[k] = undefined
        }
      })
      console.log('请求参数', params)
      const listApi = this.configData.api.request
      if (!listApi) return
      listApi(params).then(json => {
        // console.log(json, '返回表格数据')
        this.configData.initNoQuery = false
        this.tableLoading = false
        this.tableData = json.list || json
        this.total = json.totalCount
      }).catch(err => {
        if (err) {
          setTimeout(() => {
            this.tableLoading = false
          }, 5000)
        }
      })
    },
    // 多选回调
    handleSelectionChange(val) {
      /*
      * this.$refs.table.toggleRowSelection(row) 确定勾选上的内容
      * this.$refs.table.clearSelection() 清空所有的勾选
      * */
      this.$emit('selectionChange', val)
    },
    eventChange(val) {
      this.$emit('eventChange', val)
    },
    // 查询组件 onchange
    searchItemChange(value, k, item) {
      this.ruleForm[k] = value
    }
  }
}
</script>

<style scoped>
.el-button--cyan {
  background-color: #20b2aa;
  border-color: #20b2aa;
  color: #fff;
}
.el-button--cyan:hover {
    background: #48d1cc;
    border-color: #48d1cc;
}
.el-card >>> .el-card__body{
  padding: 10px 10px 0 ;
}
</style>
